package zzps.exeed.kernel.core;

import zzps.exeed.kernel.tool.ResourceTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;

public class ClassPathPluginHolderScanner extends ClassPathScanner{
    public ClassPathPluginHolderScanner(ClassLoader classLoader) {
        super(classLoader);
    }

    public List<String> scan(){
        Enumeration<URL> urlEnumeration = ResourceTool.getResources("META-INF/exeed/zzps.exeed.kernel.core.Plugin", classLoader);
//        List<String> strings = doScan("META-INF/exeed/zzps.exeed.kernel.core.Plugin");
        Iterator<URL> iterator = urlEnumeration.asIterator();
        List<String> candidates = new LinkedList<>();
        while (iterator.hasNext()) {
            URL url = iterator.next();
            readPlugin(url,candidates);
        }
        return candidates;
    }


    private List<String> readPlugin(URL url,List<String> candidates){
        try (InputStream inputStream = url.openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
            String line;
            while ((line = reader.readLine()) != null){
                line = stripComment(line);
                line = line.trim();
                if (line.isEmpty()){
                    continue;
                }
                candidates.add(line);
            }
            return candidates;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private static String stripComment(String line) {
        int commentStart = line.indexOf("#");
        if (commentStart == -1) {
            return line;
        }
        return line.substring(0, commentStart);
    }
}
